#include "StdAfx.h"
#include "Rom.h"
#include "unzip/unzip.h"
#include "crc32.h"

CRom::CRom(char *fn,u32 l,u32 s,u32 c,u32 f,char *n)
{
chksum_crc32gentab();			//todo: put this somewhere else
Data = 0;
SetInfo(fn,l,s,c,f,n);
}

CRom::CRom()
{
Data = 0;
SetInfo("",0,0,0,ROM_NOTHING,"");
}

CRom::~CRom()
{
Unload();
}

// load rom into memory
int CRom::Load(char *fn)
{
FILE *fp;

if(IsEmpty() == true)
	return(1);
if((fp = fopen(fn,"rb")) == 0)
	{
	message("error loading '%s'\n",fn);
	return(1);
	}
if(Data)
	delete[] Data;
Data = new u8[Size];
fread(Data,Size,1,fp);
fclose(fp);
message("file: loaded '%s' into $%04X ($%04X bytes)\n",fn,LoadAddr,Size);
return(0);
}

int CRom::LoadZIP(char *zipfn)
{
unzFile file;
char str[512];
u32 crc;

if(IsEmpty() == true)
	return(1);
if((file = unzOpen(zipfn)) == 0)
	{
	sprintf(str,"error opening zip file '%s'",zipfn);
	message("%s\n",str);//MessageBox(0,str,"error",MB_OK|MB_ICONERROR);
	return(1);
	}
if(unzLocateFile(file,FileName,0) == UNZ_END_OF_LIST_OF_FILE)
	{
	int found = 0;
	int ret;
	
	//try to match crc32's?
	ret = unzGoToFirstFile(file);
	while(ret == UNZ_OK)
		{
		
		unz_file_info ufi;
		
		unzGetCurrentFileInfo(file,&ufi,0,0,0,0,0,0);
		if(ufi.crc == CRC)	//crc's match, load it
			{
			found++;
			break;
			}
		ret = unzGoToNextFile(file);
		}
	if(found == 0)
		{
		sprintf(str,"error loading rom, %s is missing from '%s'",FileName,zipfn);
		message("%s\n",str);//MessageBox(0,str,"error",MB_OK|MB_ICONERROR);
		unzClose(file);
		return(1);
		}
	}
if(unzOpenCurrentFile(file) != UNZ_OK)
	{
	sprintf(str,"error loading rom, %s couldnt be opened from '%s'",FileName,zipfn);
	message("%s\n",str);//MessageBox(0,str,"error",MB_OK|MB_ICONERROR);
	unzClose(file);
	return(1);
	}
if(Data)
	delete[] Data;
Data = new u8[Size];
if(unzReadCurrentFile(file,Data,Size) != (int)Size)
	{
	delete[] Data;
	Data = 0;
	printf("error loading rom, %s couldnt be read from '%s'",FileName,zipfn);
//	MessageBox(0,str,"error",MB_OK|MB_ICONERROR);
	unzCloseCurrentFile(file);
	unzClose(file);
	return(1);
	}
unzCloseCurrentFile(file);
unzClose(file);
crc = chksum_crc32(Data,Size);
if(crc != CRC)
	message("zip: loaded '%s' into $%04X ($%04X bytes) (%s, bad CRC32)\n",FileName,LoadAddr,Size,Name);
else
	message("zip: loaded '%s' into $%04X ($%04X bytes) (%s)\n",FileName,LoadAddr,Size,Name);
return(0);
}

int CRom::LoadData(u8 *d,int len)
{
if(IsEmpty() == true)
	return(1);
if(Data)
	delete[] Data;
Size = len;
Data = d;
return(0);
}

void CRom::Unload()
{
if(Data)
	delete[] Data;
Data = 0;
}

u8 *CRom::GetData()
{
return(Data);
}

// set rom information
void CRom::SetInfo(char *fn,u32 a,u32 s,u32 c,u32 f,char *n)
{
strcpy(FileName,fn);
LoadAddr = a;
Size = s;
CRC = c;
Flags = f;
strcpy(Name,n);
}

// is there a rom loaded?
bool CRom::IsEmpty()
{
if(Flags == ROM_NOTHING)
	return(true);
return(false);
}

bool CRom::IsLoaded()
{
if(Data != 0)
	return(true);
return(false);
}
